{% extends 'base.html' %}
{% load staticfiles %}
{% block topfiles %}
    <link rel="icon" href="/static/img/logo.png" type="image/x-icon">
    <link rel="stylesheet" type="text/css" href={% static  "font-awesome/css/font-awesome.min.css" %}>

    <link rel="stylesheet" type="text/css" href={% static  "css/bootstrap-treeview.min.css" %}>
    <link rel="stylesheet" type="text/css" href={% static  "css/jquery.contextMenu.min.css" %}>
    <link rel="stylesheet" type="text/css" href={% static  "css/toastr.min.css" %}>    
    <link rel="stylesheet" type="text/css" href={% static  "css/work_1.css" %}>

    <script src={% static 'js/initializeWebWorkers.js' %}></script>
    <script src={% static 'js/bootstrap-treeview.min.js' %}></script>
    <script src={% static 'js/jquery.contextMenu.min.js' %}></script>
    <script src={% static 'js/jquery.ui.position.js' %}></script>
    <script src={% static 'js/initializeWebWorkers.js' %}></script>
    <script src={% static 'js/hammer.js' %}></script>
    <script src={% static 'js/cornerstone.js' %}></script>
    <script src={% static 'js/cornerstoneMath.min.js' %}></script>
    <script src={% static 'js/cornerstoneWADOImageLoader.min.js' %}></script>
    <script src={% static 'js/cornerstoneWebImageLoader.min.js' %}></script>
    <script src={% static 'js/cornerstoneTools.js' %}></script>
    <script src={% static 'js/dicomParser.min.js' %}></script>
    <script src={% static 'js/qwebchannel.js' %}></script>
    <script src={% static 'js/toastr.min.js' %}></script>
    <script src={% static 'js/addMouseWheel.js' %}></script>
    <style>
.overlay {
    z-index: 20;
}

.type-menu-li {
    position: relative;
    padding: 2px 5px 2px 30px;
    cursor: pointer;
} 
.type-menu-li:hover {
    background: #aaa;
}
.type-menu-li:before {
    content: '';
    position: absolute;
    top: 50%;
    left: 10px;
    margin-top: -7px;
    width: 14px;
    height: 14px;
    box-sizing: border-box;
    border: 3px solid currentColor;
}

.edit-wrapper {
    position: absolute;
    top: 0;
    left: 0;
    z-index: -10;
    opacity: 0;
    width: 100%;
    height: 100%;
    background: #000;
    overflow: hidden;
}

.edit-wrapper.is-show {
    z-index: 10;
    opacity: 1;
}

.edit-content {
    position: absolute;
    z-index: 10;
    opacity: 1;
    top: 50%;
    left: 50%;
    transform-origin: center;
}

.right-menu {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 1000;
    background: #fff;
    border-radius: 6px;
    padding: 6px 0;
    border: 1px solid #DCDFE6;
}
.right-menu.del .item {
    padding: 0 20px;
    line-height: 34px;
    cursor: pointer;
    min-width: 100px;
}
.right-menu.del .item:hover {
    background: #F5F7FA;
}
.right-menu.add .title {
    font-size: 16px;
    padding-left: 10px;
    color: #000;
    font-weight: bold;
    text-align: left;
}
.right-menu.add .list {
    max-width: 400px;
    padding: 10px 0 0 10px;
}
.right-menu.add .list:after {
    content: '';
    display: block;
    clear: both;
}
.right-menu.add .list .item {
    float: left;
    margin: 0 10px 10px 0;
    padding: 0 6px;
    line-height: 26px;
    cursor: pointer;
    border: 1px solid currentColor;
    border-radius: 4px;
}
.right-menu.add .list .item:hover {
    font-weight: bold;
}
.right-menu.add .new {
    display: flex;
    gap: 10px;
    padding: 0 10px;
}
.right-menu.add .new input {
    padding: 0 10px;
}
    </style>
{% endblock topfiles %}



{% block body %}


    <div id="blanks">
        <img class='center-in-center' src="{% static 'img/wait.gif' %}">
    </div>

    <nav class="navbar navbar-inverse">
        <div class="container-fluid">
            <div class="navbar-header" style="padding: 5px;font-size: 30px" id="left_nav">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <img style="overflow:hidden; float: left;margin-top: 5px" src="/static/img/logo.png" width="40x"
                     height="40px"/>
                <a class="navbar-brand" href="/{{ mode }}?page={{ page }}" style="font-size: 30px;"> &nbsp;X-Ray Eye</a>
            </div>


            <div class="collapse navbar-nav" id="myNavbar">
                <ul class="nav navbar-nav" style="text-align: center">

                    <li onclick="setTools(this)" id="wwwc"><a href="#" data-toggle="tooltip" data-placement="bottom"
                                                              title="调窗工具"><span
                            class="glyphicon glyphicon-eye-open"></span></i>
                    </a>

                    </li>
                    <li onclick="setTools(this)" id="pan"><a href="#" data-toggle="tooltip" data-placement="bottom"
                                                             title="平移工具"><span
                            class="glyphicon glyphicon-move"></span> </a></li>

                    <li><a href="#" id="rotate_left" data-toggle="tooltip" data-placement="bottom"
                           title="左旋转"> <i class="fa fa-mail-reply" aria-hidden="true"></i></a></li>

                    <li><a href="#" id="rotate" data-toggle="tooltip" data-placement="bottom"
                           title="右旋转"><i class="fa fa-mail-forward" aria-hidden="true"></i></a></li>

                    <li><a href="#" id="hflip" data-toggle="tooltip" data-placement="bottom"
                           title="水平翻转"> <i class="fa fa-arrows-h" aria-hidden="true"></i></a></li>

                    <li><a href="#" id="vflip" data-toggle="tooltip" data-placement="bottom"
                           title="垂直翻转"><i class="fa fa-arrows-v" aria-hidden="true"></i></a></li>

                    <li><a href="#" id="invert" data-toggle="tooltip" data-placement="bottom"
                           title="颜色反转"> <span class="glyphicon glyphicon-adjust"></span></a></li>

                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" data-toggle="tooltip"
                           data-placement="bottom"
                           title="测量工具">
                            <i class="glyphicon glyphicon-pencil"></i>
                            <b class="caret"></b>
                        </a>
                        <ul class="dropdown-menu">
                            <li id="line" onclick="line_tool()"><a href="#">直线测量</a></li>
                            <li id="eara" onclick="angle_tool()"><a href="#">角度测量</a></li>
                            <li id="eara" onclick="rect_tool()"><a href="#">区域测量</a></li>
                        </ul>
                    </li>
                    <li><a href="#" id="downloadAndView" data-toggle="tooltip" data-placement="bottom"
                           title="还原" onclick="javascript:location.reload();"> <span
                            class="glyphicon glyphicon-repeat"></span></a></li>
                </ul>
            </div>

            <div class="collapse navbar-nav" id="right_nav">
                <ul class="nav navbar-nav navbar-right">
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                            <i class="glyphicon glyphicon-cog"></i>
                            <b class="caret"></b>
                        </a>
                        <ul class="dropdown-menu">
                            <li><a href="#" data-toggle="modal" data-target="#myModal">关于</a></li>
                            <li><a href="#" data-toggle="modal" data-target="#systemModal">系统设置</a></li>
                        </ul>
                    </li>
                </ul>

            </div>
        </div>
    </nav>

    <div class="container">
        <div class="left-group">
            <ul class="list-group " style="padding: 0px;">
                <li class="list-group-item "
                    style="background-color:#333333; color: rgb(248, 245, 245);font-size: 20px;margin: 0px">
                    影像列表
                </li>
            </ul>

            <div class="test test-1 meau" id="dlist">

                {% for sopinstance in study_instance.sopinstance_set.all %}
                    <a class="sopa" onclick="go_new('{{ sopinstance.dcm_save_path }}',this)">
                        <div class='sop'>
                            <div class="sop_left" style="margin: 5px">
                                <ul style="color: aliceblue;background-color:black;display: inline-block;margin-top: 20px;">
                                    <li>{{ study_instance.study_description }}</li>
                                    <li>{{ sopinstance.inspection_site }}</li>
                                </ul>
                            </div>
                            <div class="sop_right" style="margin: 5px">
                                <img class="sop_img"
                                     src={% static  sopinstance.thumbnail_save_path %} alt='{{ sopinstance.dcm_save_path }}'/>
                            </div>
                        </div>
                    </a>
                {% endfor %}
            </div>

            <ul class="list-group " style="padding: 0px">
                <li class="list-group-item "
                    style="background-color:#333333; color: rgb(248, 245, 245);font-size: 20px;margin: 0;border-top: 1px solid #e7e7e2;">
                    检查列表
                </li>
            </ul>

            <div class="test2 test-1" id="dlist">
                <ul>
                    {% for study in study_instance.patient.studyinstance_set.all %}
                        {% if study_instance.id == study.id %}

                            <li id="study_a">
                                <a title="{{ study.study_description }}" style="color: white"
                                   href="{% url 'xray:show' study.id  mode page %}">
                                    <nobr class="col-md-12">{{ study.study_instance_time }}</nobr>
                                </a>
                            </li>
                        {% else %}
                            <li id="study_a">
                                <a title="{{ study.study_description }}"
                                   href="{% url 'xray:show' study.id  mode page %}">
                                    <nobr class="col-md-12">{{ study.study_instance_time }}</nobr>
                                </a>
                            </li>
                        {% endif %}
                    {% endfor %}

                </ul>
            </div>
        </div>


        <div class="mid-group" class="test-1">
            <input type="checkbox" id="toggleModalityLUT" style="visibility:hidden ;"></input>
            <input type="checkbox" id="toggleVOILUT" style="visibility:hidden ;"></input>
            <div style="width:100%; height:95%;text-align:center; position:relative; background-color: black;">
                 <div style="position:relative;width:100%;height:100%;" oncontextmenu="return false" class='disable-selection noIbar' unselectable='on' onselectstart='return false;' onmousedown='return false;'>
                     <div id="dicomImage" style=" width: 100%;;height:100%; ;top:0px;left:0px; position:relative">
                        <div id="topleft" class="overlay" style="position:absolute;top:0px;left:5px">
                            {{ study_instance.patient.patient_name }}
                        </div>
                        <div id="topleft" class="overlay" style="position:absolute;top:30px;left:5px">
                            {{ study_instance.patient.patient_ID }}
                        </div>
                        <div id="topleft" class="overlay" style="position:absolute;top:60px;left:5px">
                            {{ study_instance.patient.patient_sex }}
                        </div>
                        <div id="topright" class="overlay" style="position:absolute;top:0px;right:5px">
                            {{ study_instance.study_instance_time }}
                        </div>
                        <div id="topright" class="overlay" style="position:absolute;top:30px;right:5px">
                            {{ study_instance.inspection_age }}
                        </div>
                        <div id="bottomright" class="overlay" style="position:absolute;bottom:0px;right:5px">
                            Zoom:
                        </div>
                        <div id="bottomleft" class="overlay" style="position:absolute;bottom:0px;left:5px">
                            WW/WC:
                        </div>
                    </div>
                    <div class="edit-wrapper">
                      <div class="edit-content">
                        <div style="width:100%; height:100%;" class="imageContainer"></div>
                      </div>
                    </div>
                 </div>
            </div>
        </div>
        <div class="right-group ">
            <ul class="list-group ">
                <li class="list-group-item "
                    style="background-color:#333333; color: rgb(248, 245, 245);font-size: 20px;margin: 0px">
                    AI诊断结果
                </li>
            </ul>
            <div id="aiZdJg">
                <li class="list-group-item" style="background-color:#333333; color: rgb(248, 245, 245)">

                    <div style="display: inline-block;width: 100%">

                        <div class="col-md-4" style="padding: 0">
                            <div class="form-group">
                                <label style="float: left;font-size: 18px;line-height: 35px">当前阈值:</label>
                                <input type="text" value=0.1 class="form-control" id="thread"
                                       style="width: 60px; height:30px;float: left;color:black;font-size: 15px"/>
                            </div>
                        </div>

                        <div class="col-md-8" style="padding: 0">
                            <input style="" type="range" id="threshold" value="0.1" min="0.01" max="0.6"
                                   step="0.01" onchange="change_threshold()">
                            <div style="font-size: 15px">
                                <div style="display: inline-block;float: left">
                                    0.01
                                </div>
                                <div style="display: inline-block;float: right">
                                    0.6
                                </div>
                            </div>
                        </div>

                    </div>
                </li>
                <div style="display: inline-block;width: 100%;text-align: left;height: 50px;padding-top: 4px;background-color: #333333">
                    <input type='checkbox' id="chkSelectAll" onclick="selectChange();" checked="false"
                           style="width:20px;height: 40px;line-height: 40px;margin: 0 auto;float:left;margin-left: 9px"/>
                    <span style="font-size: 15px;line-height: 40px">全选/不全选</span>
                    <div style="float: right;margin-right: 20px;margin-top:3px;">
                        <button style="margin-left: 10px;font-size:18px;padding:0;height:36px;width:80px;" onclick="showEditData()" id="editRectBtn" class="btn btn-primary">编辑</button>
                        <button style="margin-left: 10px;font-size:18px;padding:0;height:36px;width:80px;display:none;" onclick="oEdit.close()" id="cancelBtn" class="btn btn-primary">取消</button>
                    </div>
                    

                </div>


                <div class="test2 test-1" id="dlist3" style=";height: 250px;background-color: #333333;margin: 0">
                    <div style="">
                        <ul class="list-group" id="detection" style="">
                        </ul>
                    </div>

                </div>
                <div id="ctr_info">

                </div>
            </div>
            <ul class="list-group " style="padding: 0px">
                <li class="list-group-item "
                    style="background-color:#333333; color: rgb(248, 245, 245);font-size: 20px;margin: 0;border-top: 1px solid #e7e7e2;">
                    AI影像表现
                </li>
            </ul>

            <div>
                {% csrf_token %}
                <div class="form-group">
                    <label for="name">影像表现:</label>

                    <textarea class="form-control"
                              rows="5"
                              id="performance" name="bx"></textarea>
                </div>

                <input type="hidden" name='sopid' value="{{ study_instance.sopinstance_set.all.0.dcm_save_path }}"
                       id="sop_id">

                <div class="form-group">
                    <label for="name">诊断意见:</label>
                    <textarea class="form-control" rows="5" name="yj" id="yj"></textarea>
                </div>
                <button id="submitBtn" style="width: 80px;font-size:15px;" type="button" class="btn btn-primary" onclick="saveForm()">提交</button>
            </div>


        </div>
    </div>
    <!-- 模态框 -->
    <div class="modal fade" id="myModal">
        <div class="modal-dialog">
            <div class="modal-content">

                <!-- 模态框头部 -->
                <div class="modal-header">
                    <h4 class="modal-title">郑重声明</h4>
                </div>

                <!-- 模态框主体 -->
                <div class="modal-body">
                    X-ray Eye系统只能用于科研和教学使用，不得用于临床诊断。
                </div>

                <!-- 模态框底部 -->
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                </div>

            </div>
        </div>
    </div>

    <!-- 系统设置模态框 -->
    <div class="modal fade" id="systemModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">系统设置</h4>
          </div>
          <div class="modal-body">
            <div style="display:flex;align-items: center;margin-bottom: 15px;">
                <div style="width:6em;text-align: right;">单位名称：</div>
                <div>
                    <input id="orgName" type="text" class="form-control" placeholder="请输入" style="width:300px;"/>
                </div>
            </div>
            <div style="display:flex;align-items: center;margin-bottom: 15px;">
                <div style="width:6em;text-align: right;">报告医生：</div>
                <div>
                    <input id="doctorName" type="text" class="form-control" placeholder="请输入" style="width:300px;"/>
                </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            <button type="button" class="btn btn-primary" onclick="saveSystemModal()">保存</button>
          </div>
        </div>
      </div>
    </div>


    <!-- 模态框 -->
    <div class="modal fade" id="confirmModal">
        <div class="modal-dialog" style="margin-top:30vh;width:350px;">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">提示</h4>
                </div>
                <div class="modal-body" style="text-align: left;min-height:90px;padding-top:30px;font-size:16px;">
                    此操作将删除该节点，是否继续？
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" onclick="saveDelete()">确定</button>
                </div>
            </div>
        </div>
    </div>

<div class="right-menu del">
    <div class="item">删除</div>
</div>
<div class="right-menu add">
    <div class="title">添加</div>
    <div class="list"></div>
    <div class="new">
        <input type="text" placeholder="自定义类型"/>
        <button class="btn btn btn-primary">确定</button>
    </div>
</div>

{% endblock %}

{% block script %}
    <script>
        document.getElementById("threshold").value = "0.50"
        $(function () {
            $('.meau').contextMenu({
                selector: 'img',
                callback: function (key, options) {
                    document.getElementById("blanks").style.setProperty("display", 'block')
                    var node = $(this).parent()[0].parentNode.parentNode
                    var dcm_path = $(this).attr('alt')

                    a = $.ajax({
                            url: "http://" + window.location.host + "/resetpredict",//json文件位置，文件名
                            type: "GET",//请求方式为get
                            dataType: "json", //返回数据格式为json
                            data: {"bw": key, "dcm_path": dcm_path},
                            async: true,
                            cache: false,
                            success: function (args) {//请求成功完成后要执行的方法
                                status = args["status"]
                                if (status) {
                                    go_new(dcm_path, node)
                                    infos[image_uir + "ctr"] = undefined
                                    change_threshold()
                                } else {
                                    alert(2)
                                }

                                document.getElementById("blanks").style.display = "none";
                            },
                            error: function () {
                                document.getElementById("blanks").style.display = "none";
                            }
                        }
                    )
                },
                items: {
                    "model1": {name: "胸部X光模型"},
                    "sep1": "---------",
                    "model2": {
                        name: "其他模型",
                    }
                }

            });
        });


        document.addEventListener("DOMContentLoaded", function () {
            //把对象赋值到JS中
            new QWebChannel(qt.webChannelTransport, function (channel) {
                window.pyjs = channel.objects.Bridge;
            });
        });

        var config = {
            "胸膜增厚": "rgb(255, 0, 255)",
            "纤维灶": "rgb(220, 20, 60)",
            "钙化": "rgb(148, 0, 211)",
            "骨折": "rgb(123, 104, 238)",
            "肺不张": "rgb(0, 0, 205)",
            "肿块": "rgb(30, 144, 255)",
            "结节": "rgb(184, 134, 11)",
            "肺气肿": "rgb(0, 139, 0)",
            "气胸": "rgb(139, 35, 35)",
            "PICC": "rgb(218, 165, 32)",
            "积液": "rgb(255, 140, 0)",
            "积气": "rgb(0, 0, 0)",
            "实变": "rgb(85, 107, 47)",
            "术后金属": "rgb(95, 158, 160)",
            "膈下游离气体": "rgb(9,113,175)",
            "肠道积气扩张": "rgb(4,248,194)",
            "肠道积液液平": "rgb(148, 0, 211)",
            "泌尿系统结石": "rgb(108,227,33)"

        }

        const baseUrl = "http://127.0.0.1:8000/static/js/";
        var image_uir = "{{ study_instance.sopinstance_set.all.0.dcm_save_path }}"

        var infos = new Array()
        _initCornerstone();
        _initInterface();
        setForm();
        var element = document.getElementById('dicomImage');
        cornerstoneTools.init();


        cornerstone.enable(element);

        cornerstone.enable(element);
        //调窗工具
        const WwwcTool = cornerstoneTools.WwwcTool;
        cornerstoneTools.addTool(WwwcTool);
        //角度工具
        const AngleTool = cornerstoneTools.AngleTool;
        cornerstoneTools.addTool(AngleTool);
        //放大工具
        const PanTool = cornerstoneTools.PanTool;
        cornerstoneTools.addTool(PanTool)

        const ZoomMouseWheelTool = cornerstoneTools.ZoomMouseWheelTool;
        cornerstoneTools.addTool(ZoomMouseWheelTool)
        cornerstoneTools.setToolActive('ZoomMouseWheel', {mouseButtonMask: 1})

        const LengthTool = cornerstoneTools.LengthTool;


        cornerstoneTools.addTool(LengthTool)
        {#cornerstoneTools.setToolActive('Length', {mouseButtonMask: 1})#}

        const RectangleRoiTool = cornerstoneTools.RectangleRoiTool;
        cornerstoneTools.addTool(RectangleRoiTool)

        document.getElementById('rotate').addEventListener('click', function (e) {
            const viewport = cornerstone.getViewport(element);
            viewport.rotation += 90;
            cornerstone.setViewport(element, viewport);
        });
        document.getElementById('invert').addEventListener('click', function (e) {
            const viewport = cornerstone.getViewport(element);
            viewport.invert = !viewport.invert;
            cornerstone.setViewport(element, viewport);
        });
        document.getElementById('rotate_left').addEventListener('click', function (e) {
            const viewport = cornerstone.getViewport(element);
            viewport.rotation -= 90;
            cornerstone.setViewport(element, viewport);
        });
        document.getElementById('hflip').addEventListener('click', function (e) {
            const viewport = cornerstone.getViewport(element);
            viewport.hflip = !viewport.hflip;
            cornerstone.setViewport(element, viewport);
        });
        document.getElementById('vflip').addEventListener('click', function (e) {
            const viewport = cornerstone.getViewport(element);
            viewport.vflip = !viewport.vflip;
            cornerstone.setViewport(element, viewport);
        });

        function disableAllTools() {
            cornerstoneTools.setToolDisabled('Wwwc');
            cornerstoneTools.setToolDisabled('Angle');
            cornerstoneTools.setToolDisabled('Length');
            cornerstoneTools.setToolDisabled('Pan');
            cornerstoneTools.setToolDisabled('RectangleRoi');

        }


        function setTools(currentNode) {
            currentNode.setAttribute("class", "active");
            elseLi = currentNode.parentNode.children
            for (var i = 0, elseLil = elseLi.length; i < elseLil; i++) {
                if (elseLi[i] !== currentNode) {//判断是否是ele节点，是否与触发事件的节点相同
                    elseLi[i].setAttribute("class", "none");

                } else {
                    elseLi[i].setAttribute("class", "active");
                    if (elseLi[i].getAttribute("id") === "wwwc") {
                        disableAllTools();
                        cornerstoneTools.setToolActive('Wwwc', {mouseButtonMask: 1})
                    } else if (elseLi[i].getAttribute("id") === "pan") {
                        disableAllTools();
                        cornerstoneTools.setToolActive('Pan', {mouseButtonMask: 1})
                    }

                }
            }

        }


        function line_tool() {
            disableAllTools();
            cornerstoneTools.setToolActive('Length', {mouseButtonMask: 1})
        }

        function angle_tool() {
            disableAllTools();
            cornerstoneTools.setToolActive('Angle', {mouseButtonMask: 1})

        }

        function rect_tool() {
            disableAllTools();
            cornerstoneTools.setToolActive('RectangleRoi', {mouseButtonMask: 1})

        }

        const baseUri = "wadouri:http://" + window.location.host + "/static"
        updateTheImage("{{ study_instance.sopinstance_set.all.0.dcm_save_path }}")
        element.addEventListener('cornerstoneimagerendered', onImageRendered);

        function updateTheImage(image_uir) {
            removeEvt()
            return cornerstone.loadAndCacheImage(baseUri + image_uir).then(function (image) {
                var viewport = cornerstone.getDefaultViewportForImage(element, image);
                cornerstone.displayImage(element, image, viewport);
            });
        }


        dlist_node = document.getElementById('dlist')
        dlist_node.firstElementChild.firstElementChild.style.border = "3px solid chartreuse"

        function go_new(dcm_image_path, obj) {
            // 编辑状态不能切换
            if(oEdit.visible) {
                toastr.warning('请先保存当前编辑内容');
                return;
            }

            image_uir = dcm_image_path
            updateTheImage(image_uir)
            removeEvt()
            element.addEventListener('cornerstoneimagerendered', onImageRendered)
            obj.firstElementChild.style.border = "3px solid chartreuse"
            siblings = allSiblings2(obj)
            for (var i = 0; i <= siblings.length - 1; i++) {
                siblings[i].firstElementChild.style.border = "3px solid rgb(134, 121, 121)"
            }

            document.getElementById("chkSelectAll").checked = true

        }

        function allSiblings2(tag) {
            var parent = tag.parentNode;
            var bro = parent.children;
            var siblings = [];
            for (var i = 0; i <= bro.length - 1; i++) {
                if (bro[i] != tag) {
                    siblings.push(bro[i]);
                }
            }
            return siblings;
        }

        function polygon(image_uir, context, thresold) {
            objects1 = []
            var temp_uri = "http://" + window.location.host + "/static" + image_uir + ".json"
            a = $.ajax({
                    url: temp_uri,//json文件位置，文件名
                    type: "GET",//请求方式为get
                    dataType: "json", //返回数据格式为json
                    async: false,
                    cache: false,
                    success: function (data) {//请求成功完成后要执行的方法
                        objects = data["objects"].map((item, index) => {
                            item.index = index;
                            return item;
                        })
                        objects1 = objects
                        objects.sort(up)
                        drawBoundingBox(objects, context, true, thresold)
                        //心胸比
                        ctr = data['ctr']
                        infos[image_uir + "ctr"] = ctr

                        infos[image_uir + "model"] = true

                        oEdit.init();
                    },
                    error: function () {
                        objects = []
                        objects1 = objects
                        drawBoundingBox([], context, true, thresold)
                        infos[image_uir + "model"] = false

                    }
                }
            )
            ;
        }

        // 升序排列
        function up(a, b) {
            return a.val - b.val
        }


        // 降序排列
        function down(a, b) {
            return b.val - a.val
        }



        // 是否已绑定事件
        var isBind = false;
        var aPath = [];
        var path = null;

        function drawBoundingBox(objects, context, flag, threshold) {
            if (flag) {
                infos[image_uir + "_current"] = []
            }
            try {
                objects.length;
            } catch (e) {
                return
            }
            contentes = ""


            for (i = 0; i < objects.length; i++) {
                confidence = objects[i]["confidence"]
                name1 = objects[i]["name"]
                color = config[name1] || 'rgb(0,0,0)'
                if(objects[i].isDelete) {
                    continue;
                }
                if (color == undefined) {
                    color = "rgb(0, 0, 0)"
                }
                if (confidence < threshold) {
                    continue;
                }
                if (confidence === 1) {
                    label = objects[i]["name"]
                } else {
                    label = objects[i]["name"] + " " + confidence.toString()
                }

                xmin = objects[i]["xmin"]
                ymin = objects[i]["ymin"]
                xmax = objects[i]["xmax"]
                ymax = objects[i]["ymax"]

                if (flag) {
                    objects[i]["mark"] = true
                    infos[image_uir + "_current"].push(objects[i])
                }


                if (!objects[i]["mark"]) {
                    contentes += " <li class='list-group-item'style='background:" + color + ";margin:0 10px;width: 470px'>" +
                        "<div style='float:left'><input type='checkbox' name ='chkItem'  style='width: 20px;height: 20px;margin: 0 auto'  onclick='selectOneChange()' />" +
                        "</div><span style='font-size:18px;color:white;font-weight: 550' >" + label + "</span><br/>" +
                        `</li>`;

                    continue
                } else {
                    contentes += " <li class='list-group-item'style='background:" + color + ";margin:0 10px;width: 470px'>" +
                        "<div style='float:left'><input type='checkbox' name ='chkItem' checked='true' style='width: 20px;height: 20px;margin: 0 auto'  onclick='selectOneChange()' />" +
                        "</div><span style='font-size:18px;color:white;font-weight: 550' >" + label + "</span><br/>" +
                        `</li>`;
                }

                context.fillStyle = color;
                context.strokeStyle = color;
                context.lineWidth = 8;
                context.font = "60px 微软雅黑"
                context.beginPath();
                context.moveTo(xmin, ymin);
                context.lineTo(xmin, ymax);
                context.lineTo(xmax, ymax);
                context.lineTo(xmax, ymin);
                context.lineTo(xmin, ymin);
                context.fillText(label, xmin, ymin - 1)
                context.fillRect(xmin, ymin - 60, context.measureText(label).width, 60);
                context.closePath();
                context.stroke();
                context.fillStyle = "white"
                context.fillText(label, xmin, ymin - 1)

                // 添加上、右、下、左移动
                path = new Path2D();
                path.rect(xmin, ymin-6, xmax-xmin, 12);
                aPath.push({
                    path: path,
                    index: i
                });
                path = new Path2D();
                path.rect(xmax-6, ymin, 12, ymax-ymin);
                aPath.push({
                    path: path,
                    index: i
                });
                path = new Path2D();
                path.rect(xmin, ymax-6, xmax-xmin, 12);
                aPath.push({
                    path: path,
                    index: i
                });
                path = new Path2D();
                path.rect(xmin-6, ymin, 12, ymax-ymin);
                aPath.push({
                    path: path,
                    index: i
                });
            }

            document.getElementById("detection").innerHTML = contentes

            // if(!isBind) {
            //     isBind = true;
            //     $('#dicomImage').on('contextmenu', 'canvas', (e) => {
            //         e.preventDefault();
            //         e.stopPropagation();
            //         var canvas = e.target;
            //         var context = canvas.getContext('2d');
            //         var rect = canvas.getBoundingClientRect();
            //         var x = e.clientX - rect.left;
            //         var y = e.clientY - rect.top;

            //         let index = -1;
            //         aPath.forEach((item) => {
            //           if(context.isPointInPath(item.path, x, y)) {
            //             index = item.index;
            //           }
            //         })
            //         if(index == -1) {
            //             $(".right-menu.add").css({
            //                 top: e.pageY+'px',
            //                 left: e.pageX+'px'
            //             })
            //             $('.right-menu.add').show();
            //         } else {
            //             $('.right-menu.del').css({
            //                 top: e.pageY+'px',
            //                 left: e.pageX+'px'
            //             })
            //             $('.right-menu.del').show();
            //             deleteIndex = index;
            //         }
            //     })
            // }
        }

        function removeEvt() {
            element.removeEventListener('cornerstoneimagerendered', onImageRendered);
            element.removeEventListener('cornerstoneimagerendered', onImageRendered2);
            element.removeEventListener('cornerstoneimagerendered', onImageRendered3);

        }

        function change_threshold() {
            removeEvt()
            flag2 = true
            document.getElementById('thread').value = document.getElementById("threshold").value
            infos[image_uir] = document.getElementById("threshold").value
            updateTheImage(image_uir)
            element.addEventListener('cornerstoneimagerendered', onImageRendered);

        }

        var flag2 = true
        var imgZoom = 1; // 缩放分大小
        var imgInfo = {
            width: 0,
            height: 0
        }

        function onImageRendered(e) {
            imgInfo.width = e.detail.image.width;
            imgInfo.height = e.detail.image.height;

            // 初始化编辑
            oEdit.init(e);

            const eventData = e.detail;
            cornerstone.setToPixelCoordinateSystem(eventData.enabledElement, eventData.canvasContext);
            const context = eventData.canvasContext;
            threshold = infos[image_uir]
            if (threshold === undefined) {
                threshold = 0.1
                infos[image_uir] = threshold
            }
            document.getElementById("threshold").value = threshold
            document.getElementById("thread").value = threshold

            if (infos[image_uir + "_current"] === undefined || flag2) {
                polygon(image_uir, context, threshold);
                flag2 = false
            } else {
                drawBoundingBox(infos[image_uir + "_current"], context, true, threshold)
            }


            if (infos[image_uir + "ctr"] === undefined) {
                ctr_info = document.getElementById("ctr_info")
                ctr_info.innerHTML = ''
            } else {
                ctr = infos[image_uir + "ctr"]
                ratio = ctr['ratio']
                setXxb(ratio);
            }


            document.getElementById('bottomleft').textContent = "WW/WL:" + Math.round(eventData.viewport.voi.windowWidth) + "/" + Math.round(eventData.viewport.voi.windowCenter);
            document.getElementById('bottomright').textContent = "Zoom:" + eventData.viewport.scale.toFixed(2);
            imgZoom = eventData.viewport.scale;

            updatePerformance()
        }

        // 设置心胸比
        function setXxb(ratio) {
            var text = "";
            var checked = false;
            if($('#ctr_select').length) {
                checked = $('#ctr_select').is(':checked');
            }

            if (0.5 < ratio && ratio <= 0.55) {
                text = "<span id ='ctr_text' style='font-size: 25px;color:yellow'>&emsp; 心胸比:" + ratio.toFixed(2).toString() + "(轻度增大)</span>\n"
            } else if (0.55 < ratio && ratio <= 0.6) {
                text = "<span id ='ctr_text' style='font-size: 25px;color:orange'>&emsp; 心胸比:" + ratio.toFixed(2).toString() + "(中度增大)</span>\n"
            } else if (ratio > 0.6) {
                text = "<span id ='ctr_text' style='font-size: 25px;color:red'>&emsp; 心胸比:" + ratio.toFixed(2).toString() + "(重度增大)</span>\n"
            } else if (ratio < 0.5) {
                text = "<span id ='ctr_text' style='font-size: 25px;color:yellowgreen'>&emsp; 心胸比:" + ratio.toFixed(2).toString() + "(正常)</span>\n"
            } else if (1 < ratio) {
                text = "<span id ='ctr_text' style='font-size: 25px;color:red'>&emsp; 心胸比计算错误</span>\n"
            } else {
                text = "<span id ='ctr_text' style='font-size: 25px;color:red'>&emsp; 心胸比计算错误</span>\n"
            }
            var ctr_info = document.getElementById("ctr_info")
            ctr_info.innerHTML = "<div id='ctr' style='position:relative;text-align: left; height: 40px;line-height: 40px;background-color: #333333;border-top: 1px solid white'>\n" +
                `                        <input type='checkbox' id='ctr_select' ${checked ? 'checked' : ''} onclick='ctr_select()'` +
                "                               style=\"width:20px;height: 40px;line-height: 40px;margin: 0 auto;float:left;margin-left: 9px\"/>\n" +
                "                        <span style=\"font-size: 15px;line-height: 40px;text-align: left\">显示/不显示</span>\n" + text + "</div>"
        }


        function onImageRendered2(e) {
            const eventData = e.detail;
            cornerstone.setToPixelCoordinateSystem(eventData.enabledElement, eventData.canvasContext);
            const context = eventData.canvasContext;
            threshold = infos[image_uir]
            drawBoundingBox(infos[image_uir + '_current'], context, false, threshold)
            imgZoom = eventData.viewport.scale;
        }


        function onImageRendered3(e) {
            const eventData = e.detail;
            cornerstone.setToPixelCoordinateSystem(eventData.enabledElement, eventData.canvasContext);
            const context = eventData.canvasContext;
            drawBoundingBox(infos[image_uir + '_current'], context, false, threshold)
            drawCTR(infos[image_uir + "ctr"], context)
            imgZoom = eventData.viewport.scale;
        }


        function selectAllItem() {
            var items = document.getElementsByName("chkItem");
            for (var i = 0; i < items.length; i++) {
                items[i].checked = true;
            }
            selectOneChange()
            updateTheImage(image_uir)
            removeEvt()
            element.addEventListener('cornerstoneimagerendered', onImageRendered2);
        }

        function selectChange() {
            var chkSelectAll = document.getElementById("chkSelectAll");
            var checked = chkSelectAll.checked
            if (checked) {
                selectAllItem();
                chkSelectAll.checked = true
            } else {
                unSelectAll();
                chkSelectAll.checked = false
            }

        }


        function unSelectAll() {
            var items = document.getElementsByName("chkItem");
            for (var i = 0; i < items.length; i++) {
                items[i].checked = false;
            }
            selectOneChange()
            removeEvt()
            updateTheImage(image_uir)
            element.addEventListener('cornerstoneimagerendered', onImageRendered2);

            if (document.getElementById("ctr").checked) {
                element.addEventListener('cornerstoneimagerendered', onImageRendered2)
            }

        }


        function selectOneChange() {
            var items = document.getElementsByName("chkItem");
            var a = 0
            for (var i = 0; i < items.length; i++) {
                if (items[i].checked == true) {
                    infos[image_uir + "_current"][i]["mark"] = true;
                    a += 1
                } else {
                    infos[image_uir + "_current"][i]["mark"] = false;
                }
            }
            //
            if (a === 0) {
                var chkSelectAll = document.getElementById("chkSelectAll");
                chkSelectAll.checked = false;
            }

            if (a === items.length) {
                var chkSelectAll = document.getElementById("chkSelectAll");
                chkSelectAll.checked = true;
            }
            removeEvt();
            updateTheImage(image_uir)
            element.addEventListener('cornerstoneimagerendered', onImageRendered2);
            updatePerformance()

        }


        function update_reports() {
            var performance = document.getElementById("performance")
            var items = document.getElementsByName("chkItem");

            //遍历诊断结果

        }

        function ctr_select() {
            var ctr = document.getElementById("ctr_select");
            var checked = ctr.checked;
            drawReload(checked);
        }
        // 切换心胸比，重绘
        function drawReload(state) {
            if (state) {
                updateTheImage(image_uir)
                removeEvt()
                element.addEventListener('cornerstoneimagerendered', onImageRendered3);
            } else {
                removeEvt()
                updateTheImage(image_uir)
                element.addEventListener('cornerstoneimagerendered', onImageRendered2);
            }
        }

        function drawCTR(ctr, context) {
            contentes = ""
            context.beginPath();
            context.lineWidth = 6;
            context.strokeStyle = "green"
            context.moveTo(ctr["lung_x_begin"], ctr["lung_y"]);
            context.lineTo(ctr["lung_x_end"], ctr["lung_y"]);
            context.closePath();
            context.stroke();
            centerX = (ctr["lung_x_begin"] + ctr["lung_x_end"]) / 2
            Y = [ctr["lung_y"], ctr["heart_y_begin_left"], ctr["heart_y_end_right"]]
            minY = Math.min(...Y)
            maxY = Math.max(...Y)
            context.strokeStyle = "black"
            context.beginPath();
            context.moveTo(centerX, minY - 50);
            context.lineTo(centerX, maxY + 50);
            context.closePath();
            context.stroke();
            context.strokeStyle = "red"
            context.beginPath();
            context.moveTo(ctr["heart_x_begin_left"], ctr["heart_y_begin_left"]);
            context.lineTo(centerX, ctr["heart_y_begin_left"]);
            context.closePath();
            context.stroke();
            context.beginPath();
            context.moveTo(centerX, ctr["heart_y_end_right"]);
            context.lineTo(ctr["heart_x_end_right"], ctr["heart_y_end_right"]);
            context.closePath();
            context.stroke();
        }


        function _initCornerstone() {
            // Externals
            cornerstoneWADOImageLoader.external.cornerstone = cornerstone;
            cornerstoneWADOImageLoader.external.dicomParser = dicomParser;
            cornerstoneTools.external.cornerstoneMath = cornerstoneMath;
            cornerstoneTools.external.cornerstone = cornerstone;
            cornerstoneTools.external.Hammer = Hammer;

            // Image Loader
            const config = {
                webWorkerPath: `${baseUrl}assets/image-loader/cornerstoneWADOImageLoaderWebWorker.js`,
                taskConfiguration: {
                    decodeTask: {
                        codecsPath: `${baseUrl}assets/image-loader/cornerstoneWADOImageLoaderCodecs.js`,
                    },
                },
            };
            cornerstoneWADOImageLoader.webWorkerManager.initialize(config);
        }

        /***
         *
         *
         */
        function _initInterface() {
            const handleClick = function (evt) {
                const action = this.dataset.action;
                const options = {
                    mouseButtonMask:
                        evt.buttons || convertMouseEventWhichToButtons(evt.which),
                };

                cornerstoneTools[`setTool${action}`](toolName, options);

                // Remove active style from all buttons
                const buttons = document.querySelectorAll('.set-tool-mode');
                buttons.forEach(btn => {
                    btn.classList.remove('is-primary');
                });

                // Add active style to this button
                this.classList.add('is-primary');

                evt.preventDefault();
                evt.stopPropagation();
                evt.stopImmediatePropagation();
                return false;
            };
            const buttons = document.querySelectorAll('.set-tool-mode');
            buttons.forEach(btn => {
                btn.addEventListener('contextmenu', handleClick);
                btn.addEventListener('auxclick', handleClick);
                btn.addEventListener('click', handleClick);
            });
        }

        function editRect() {
            var str1 = JSON.stringify(infos[image_uir + '_current']);
            pyjs.jsCallpy(str1 + "__" + image_uir, function (result) {
            });            
        }

        var performanceNode = document.getElementById('performance')

        function updatePerformance() {
            var f = false
            var ctr_text = ''
            try {
                ctr_text = document.getElementById('ctr_text').textContent

                var ctr = ctr_text.substring(6, 10)

                if (parseFloat(ctr) < 0.5) {
                    var consequence = "不大"
                    f = true
                } else {
                    var consequence = ctr_text.substring(11, 15)
                }

                ctr_context = "心影" + consequence + ",心胸比为:" + ctr + "。"
            } catch (e) {
                ctr_context = ""
            }


            var focus = []
            var context = "该影像疑似有"
            var currents = infos[image_uir + '_current']
            for (var i = 0; i < currents.length; i++) {
                if (currents[i]['mark']) {
                    focus.push(currents[i]['name'])
                }
            }

            var nidus = Array.from(new Set(focus))
            performanceNode.innerText = context

            for (var j = 0; j < nidus.length; j++) {
                if (j == nidus.length - 1) {
                    context += nidus[j] + "病灶征象。" + ctr_context
                } else {
                    context += nidus[j] + "、"
                }

            }


            if (nidus.length == 0 && f) {
                performanceNode.innerText = "该影像未见明显异常。" + ctr_context
            } else if (nidus.length == 0 && ctr_context.length != 0) {
                performanceNode.innerText = ctr_context
            } else {
                performanceNode.innerText = context
            }

            if (!infos[image_uir + "model"]) {
                performanceNode.innerText = "该影像未警告模型推理，请谨慎诊断！"
            }

            if (context === "该影像疑似有") {
                performanceNode.innerText = "该影像未见明显异常!"
            }

        }

        // 显示编辑框
        function showEditData() {
            if(!oEdit.visible) {
                oEdit.show({
                    data: {
                        line: infos[image_uir + "ctr"],
                        rect: infos[image_uir + "_current"]
                    },
                    showLine: $('#ctr_select').is(':checked')
                })
            } else {
                oEdit.save();
                saveDiagnosisData();
            }
        }

        const oEdit = {
            visible: false,
            isInit: false,

            oWrapper: $('.edit-wrapper'),
            oPosition: $('.edit-wrapper .edit-position'),
            oContent: $('.edit-wrapper .edit-content'),
            oContainer: $('.edit-wrapper .imageContainer'),
            oTarget: null,
            oCanvas: null,
            context: null,

            // 是否添加矩形
            isAddRect: false,
            editRectIndex: -1,
            add: {
                name: '',
                top: 0,
                left: 0,
                downx: 0,
                downy: 0,
                movex: 0,
                movey: 0
            },

            // 删除下标
            deleteIndex: -1,

            // 图片数据
            image: {
              ratio: 0,
              leftDis: 0,
              topDis: 0,
              width: 0,
              height: 0,
              file: null
            },
            // 是否显示线
            showLine: false,
            // 数据
            oldData: null,
            newData: null,
            startData: null,
            // 路径
            paths: [],
            oPath: null,
            // 显示
            show(options) {
                // 判断是否重置图片位置
                if(options.reloadPosition !== false) {
                    this.setImagePosition();
                }

                this.showLine = options.showLine; // 是否显示线
                this.oldData = JSON.parse(JSON.stringify(options.data));
                this.newData = JSON.parse(JSON.stringify(options.data));

                // 设置初始编辑为-1
                this.editRectIndex = ('editRectIndex' in options) ? options.editRectIndex : -1;

                this.drawData();

                this.visible = true;

                this.oWrapper.addClass('is-show');

                $('#submitBtn').hide();
                $('#myNavbar > .nav').hide();
                $('#addDornwBox').hide();
                $('#aiZdJg input[type="checkbox"]').attr('disabled', true);
                $('#thread').attr('disabled', true); // 设置阈值不能编辑
                $('#threshold').attr('disabled', true); // 设置阈值不能编辑
                $('#cancelBtn').show();
                $('#editRectBtn').text('保存');
            },
            // 画
            addRect(name) {
                this.oWrapper.addClass('is-show');

                this.isAddRect = true;
                this.add.name = name;
                // 画图
                this.drawData(true);
                this.visible = true;

                $('#submitBtn').hide();
                $('#myNavbar > .nav').hide();
                $('#addDornwBox').hide();
                $('#aiZdJg input[type="checkbox"]').attr('disabled', true);
                $('#thread').attr('disabled', true); // 设置阈值不能编辑
                $('#threshold').attr('disabled', true); // 设置阈值不能编辑
                $('#cancelBtn').show();
                $('#editRectBtn').text('保存');
            },
            // 关闭
            close() {
                this.oWrapper.removeClass('is-show');

                $('#submitBtn').show();
                $('#myNavbar > .nav').show();
                $('#addDornwBox').show();
                $('#aiZdJg input[type="checkbox"]').attr('disabled', false);
                $('#thread').attr('disabled', false); // 设置阈值可以编辑
                $('#threshold').attr('disabled', false); // 设置阈值可以编辑
                $('#cancelBtn').hide();
                $('#editRectBtn').text('编辑');
                drawReload($('#ctr_select').is(':checked'));
                this.isAddRect = false;
                this.visible = false;

                // 保存心胸比
                try {
                    setXxb(infos[image_uir + "ctr"].ratio);
                } catch (e) {
                    console.log(e);
                }
            },
            // 保存
            save() {
                infos[image_uir + "ctr"] = this.newData.line;
                infos[image_uir + "_current"] = this.newData.rect;
                this.close();
            },
            // 初始化
            async init(e) {
                // if(this.isInit) {
                //     return;
                // }
                if(!e) {
                    return;
                }
                this.isInit = true;
                await this.initImageData(e);
                await waitTimeout(50);

                this.initEvent();
            },
            initEvent() {
              // 缩放大小
              addMouseWheel(this.oWrapper[0], (delta) => {
                let scale = this.scale;
                if(delta > 0) {
                  scale += 0.05;
                } else if(delta < 0) {
                  scale -= 0.05;
                }
                if(scale >= 2) {
                  scale = 2;
                }
                if(scale <= this.image.ratio) {
                  scale = this.image.ratio;
                }
                this.scale = scale;
                this.oContent.css({
                  transform: `translate(-50%, -50%) scale(${scale})`
                })
              })

              // 拖动
              let cIsDown = false;
              let cdownx = 0, cdowny = 0;
              let startLeft = 0, startTop = 0;
              this.oWrapper.on('mousedown', (e) => {
                if(isDown) {
                  return;
                }
                cIsDown = true;
                cdownx = e.pageX;
                cdowny = e.pageY;
                startLeft = parseInt(this.oContent.css('left'));
                startTop = parseInt(this.oContent.css('top'));
              })

              window.addEventListener('mousemove', (e) => {
                if(cIsDown) {
                  var movex = e.pageX - cdownx + startLeft;
                  var movey = e.pageY - cdowny + startTop;
                  this.oContent.css({
                    left: movex+'px',
                    top: movey+'px'
                  })
                }
              })


              var context = this.context;
              var isDown = false;
              var downx = 0, downy = 0;

              // 点击选中编辑方框
              $(this.oCanvas).on('click', (e) => {
                if(!this.visible || isDown) {
                    return;
                }
                var canvas = this.oCanvas;
                var rect = canvas.getBoundingClientRect();
                var x = (e.clientX - rect.left) / this.scale;
                var y = (e.clientY - rect.top) / this.scale;
                this.paths.forEach((item) => {
                  if(context.isPointInPath(item.path, x, y)) {
                    if(item.cursor == 'pointer') {
                      // 设置编辑框下标
                      this.editRectIndex = item.index;
                      // 画数据
                      this.drawData();
                    }
                  }
                })
              })

              $(this.oCanvas).on('mousedown', (e) => {
                if(!this.visible) {
                    return;
                }
                var canvas = this.oCanvas;
                var rect = canvas.getBoundingClientRect();
                var x = (e.clientX - rect.left) / this.scale;
                var y = (e.clientY - rect.top) / this.scale;
                if(this.isAddRect) {
                    isDown = true;
                    this.add.left = rect.left;
                    this.add.top = rect.top;
                    this.add.downx = e.pageX;
                    this.add.downy = e.pageY;
                } else {
                  this.paths.forEach((item) => {
                    if(item.cursor != 'pointer') {
                        if(context.isPointInPath(item.path, x, y)) {
                          this.oPath = item;
                          isDown = true;
                          this.startData = JSON.parse(JSON.stringify(this.newData));
                          downx = e.pageX;
                          downy = e.pageY;
                        }
                    }
                  })
                }
              })

              $(this.oCanvas).on('mousemove', (e) => {
                if(!this.visible) {
                    return;
                }
                if(this.isAddRect && isDown) {
                    let movex = (e.pageX - this.add.downx) / this.scale;
                    let movey = (e.pageY - this.add.downy) / this.scale;
                    this.add.xmin = (this.add.downx - this.add.left) / this.scale;
                    this.add.ymin = (this.add.downy - this.add.top) / this.scale;
                    this.add.xmax = (this.add.downx - this.add.left) / this.scale + movex;
                    this.add.ymax = (this.add.downy - this.add.top) / this.scale + movey;
                    // 画只有图像的数据
                    this.drawData(true);
                    this.drawAddRect();
                } else {
                  // 如果当前是按下
                  if(isDown) {
                    var movex = (e.pageX - downx) / this.scale;
                    var movey = (e.pageY - downy) / this.scale;
                    // 保存线数据
                    if(this.oPath.type == 'line') {
                      this.saveLineData(this.oPath.key, this.oPath.dir, movex, movey);
                    
                    // 保存矩形数据
                    } else if (this.oPath.type == 'rect') {
                      this.saveRectData(this.oPath, movex, movey);
                    }
                  } else { // 非按下，移动改变canvas鼠标形状
                    var canvas = this.oCanvas;
                    var rect = canvas.getBoundingClientRect();
                    var x = (e.clientX - rect.left) / this.scale;
                    var y = (e.clientY - rect.top) / this.scale;
                    for(var i = 0; i < this.paths.length; i++) {
                      var item = this.paths[i];
                      if(context.isPointInPath(item.path, x, y)) {
                        canvas.style.cursor = item.cursor;
                        break;
                      } else {
                        canvas.style.cursor = '';
                      }
                    }
                  }
                }
              })

              window.addEventListener('mouseup', () => {
                if(!this.visible) {
                    return;
                }
                cIsDown = false;
                isDown = false;
                // 如果是添加矩形，鼠标抬起后，绘制可拖拽数据
                if(this.isAddRect) {
                    // 添加数据
                  this.newData.rect.push({
                    name: this.add.name,
                    mark: true,
                    confidence: 1.0,
                    xmin: (this.add.xmin-this.image.leftDis),
                    ymin: (this.add.ymin-this.image.topDis),
                    xmax: (this.add.xmax-this.image.leftDis),
                    ymax: (this.add.ymax-this.image.topDis),
                  })
                  this.isAddRect = false;
                  // 画图形
                  oEdit.show({
                    data: this.newData,
                    showLine: $('#ctr_select').is(':checked'),
                    editRectIndex: this.newData.rect.length - 1,
                    reloadPosition: false, // 设置不更新图像定位
                  });
                }
              })

              // 右键弹出菜单
              this.oWrapper.on('contextmenu', 'canvas', (e) => {
                e.preventDefault();
                e.stopPropagation();
                var canvas = this.oCanvas;
                var rect = canvas.getBoundingClientRect();
                var x = (e.clientX - rect.left) / this.scale;
                var y = (e.clientY - rect.top) / this.scale;
                let i = -1;
                this.paths.forEach((item) => {
                  if(context.isPointInPath(item.path, x, y)) {
                    if(item.cursor == 'move' || item.cursor == 'pointer') {
                        i = item.index;
                    }
                  }
                })
                $('.right-menu').hide();
                if(i == -1) {
                  $('.right-menu.add').css({
                    top: e.pageY+'px',
                    left: e.pageX+'px'
                  })
                  $('.right-menu.add').show();
                } else {
                  $('.right-menu.del').css({
                    top: e.pageY+'px',
                    left: e.pageX+'px'
                  })
                  $('.right-menu.del').show();
                  this.deleteIndex = i;
                }
              })
            },

            // 初始化图片宽高
            async initImageData(e) {
              var image = e.detail.image;

              // 保存图片宽高
              this.image.width = e.detail.image.width;
              this.image.height = e.detail.image.height;

              this.oTarget = e.target;
              this.image.ratio = e.detail.viewport.scale;
              
              this.setImagePosition();

              // 设置图片
              cornerstone.enable(this.oContainer[0]);
              var viewport = cornerstone.getDefaultViewportForImage(this.oContainer[0], image);
              cornerstone.displayImage(this.oContainer[0], image, viewport);
              await waitTimeout(50);

              // 获取ctx对象
              this.oCanvas = this.oContainer[0].children[0];
              this.context = this.oCanvas.getContext('2d');
              // 保存图片
              var base64 = this.oCanvas.toDataURL('image/png');
              var img = new Image();
              img.src = base64;
              img.onload = () => {
                this.image.file = img;
                this.image.leftDis = (img.width-this.image.width)/2;
                this.image.topDis = (img.height-this.image.height)/2;
              }
            },

            // 设置图片大小位置
            setImagePosition() {
              let ratio = this.image.ratio;
              // 设置宽高
              this.oContent.width(this.oTarget.clientWidth/ratio);
              this.oContent.height(this.oTarget.clientHeight/ratio);
              // 设置比例
              this.oContent.css({
                transform: `translate(-50%, -50%) scale(${ratio})`,
                left: '50%',
                top: '50%'
              })
              // 设置缩放大小
              this.scale = ratio;
            },

            // 保存线数据
            saveLineData(key, dir, movex, movey) {
                let oLine = this.newData.line;
                let startLine = this.startData.line;
                // 保存线位置数据
                oLine[key] = (dir == 'x' ? movex : movey) + startLine[key];
                // 计算心胸比
                oLine.ratio = (oLine.heart_x_end_right - oLine.heart_x_begin_left) / (oLine.lung_x_end - oLine.lung_x_begin);

                // 设置心胸比
                setXxb(oLine.ratio);

                // 画数据
                this.drawData();
            },

            // 保存矩形数据
            saveRectData(path, movex, movey) {
                let oRect = this.newData.rect;
                let startRect = this.startData.rect;
                var index = path.index;
                if(path.dir == 'xy') {
                    if(path.key instanceof Array) {
                        let xkey = path.key[0], ykey = path.key[1];
                        oRect[index][xkey] = movex+startRect[index][xkey];
                        oRect[index][ykey] = movey+startRect[index][ykey];                    
                    } else {
                        oRect[index].xmin = movex+startRect[index].xmin;
                        oRect[index].xmax = movex+startRect[index].xmax;
                        oRect[index].ymin = movey+startRect[index].ymin;
                        oRect[index].ymax = movey+startRect[index].ymax;
                    }
                } else {
                    oRect[index][path.key] = (path.dir == 'x' ? movex : movey)+startRect[index][path.key];
                }

                // 画数据
                this.drawData();
            },

            // 删除
            deleteRectData() {
                this.newData.rect[this.deleteIndex].isDelete = true;
                // 画数据
                this.drawData();
            },

            // 画数据
            drawData(onlyImg) {
                this.paths = [];
                // 清空画布
                this.oCanvas.width = this.oCanvas.width;
                // 绘制底图
                this.drawImage();
                // 画线，画框
                this.drawRect(this.newData.rect, onlyImg);
                if(this.showLine) {
                    this.drawLine(this.newData.line, onlyImg);
                }
            },

            // 绘制底图
            drawImage() {
              this.context.drawImage(this.image.file,0,0);
            },

            // 画线
            drawLine(data, onlyImg) {
              var ctr = {
                lung_x_begin: data.lung_x_begin+this.image.leftDis,
                lung_x_end: data.lung_x_end+this.image.leftDis,
                lung_y: data.lung_y+this.image.topDis,
                heart_x_begin_left: data.heart_x_begin_left+this.image.leftDis,
                heart_x_end_right: data.heart_x_end_right+this.image.leftDis,
                heart_y_begin_left: data.heart_y_begin_left+this.image.topDis,
                heart_y_end_right: data.heart_y_end_right+this.image.topDis,
              };
              var context = this.context;
              var paths = [];

              var path = null;

              let size1 = 6;
              let size2 = 20;
              let size3 = 6;
              let size4 = 50;

              context.beginPath();
              context.lineWidth = size1;
              context.strokeStyle = "green"
              context.moveTo(ctr.lung_x_begin, ctr.lung_y);
              context.lineTo(ctr.lung_x_end, ctr.lung_y);
              context.closePath();
              context.stroke();

              centerX = (ctr.lung_x_begin + ctr.lung_x_end) / 2
              Y = [ctr.lung_y, ctr.heart_y_begin_left, ctr.heart_y_end_right]
              minY = Math.min(...Y)
              maxY = Math.max(...Y)
              context.strokeStyle = "black"
              context.beginPath();
              context.moveTo(centerX, minY - size4);
              context.lineTo(centerX, maxY + size4);
              context.closePath();
              context.stroke();

              context.strokeStyle = "red"
              context.beginPath();
              context.moveTo(ctr.heart_x_begin_left, ctr.heart_y_begin_left);
              context.lineTo(centerX, ctr.heart_y_begin_left);
              context.closePath();
              context.stroke();

              context.beginPath();
              context.moveTo(centerX, ctr.heart_y_end_right);
              context.lineTo(ctr.heart_x_end_right, ctr.heart_y_end_right);
              context.closePath();
              context.stroke();
          
              if(!onlyImg) {
                // ------------------------------
                  // 绿色左
                  context.beginPath();
                  context.arc(ctr.lung_x_begin, ctr.lung_y, size3*4, 0, 2*Math.PI);
                  context.closePath();
                  context.lineWidth = size3;
                  context.strokeStyle = '#ffffff';
                  context.stroke();
                  // 添加路径
                  path = new Path2D();
                  path.arc(ctr.lung_x_begin, ctr.lung_y, size3*4, 0, 2*Math.PI);
                  paths.push({
                    type: 'line',
                    cursor: 'e-resize',
                    dir: 'x',
                    path: path,
                    key: 'lung_x_begin'
                  });
                  // 绿色右
                  context.beginPath();
                  context.arc(ctr.lung_x_end, ctr.lung_y, size3*4, 0, 2*Math.PI);
                  context.closePath();
                  context.lineWidth = size3;
                  context.strokeStyle = '#ffffff';
                  context.stroke();
                  // 添加路径
                  path = new Path2D();
                  path.arc(ctr.lung_x_end, ctr.lung_y, size3*4, 0, 2*Math.PI);
                  paths.push({
                    type: 'line',
                    cursor: 'e-resize',
                    dir: 'x',
                    path: path,
                    key: 'lung_x_end'
                  });
                  // 绿色中
                  context.beginPath();
                  context.arc(ctr.lung_x_begin+(ctr.lung_x_end-ctr.lung_x_begin)/2, ctr.lung_y, size3*4, 0, 2*Math.PI);
                  context.closePath();
                  context.lineWidth = size3;
                  context.strokeStyle = '#ffffff';
                  context.stroke();
                  // 添加路径
                  path = new Path2D();
                  path.arc(ctr.lung_x_begin+(ctr.lung_x_end-ctr.lung_x_begin)/2, ctr.lung_y, size3*4, 0, 2*Math.PI);
                  paths.push({
                    type: 'line',
                    cursor: 'n-resize',
                    dir: 'y',
                    path: path,
                    key: 'lung_y'
                  });


                  // 红色左
                  context.beginPath();
                  context.arc(ctr.heart_x_begin_left, ctr.heart_y_begin_left, size3*4, 0, 2*Math.PI);
                  context.closePath();
                  context.lineWidth = size3;
                  context.strokeStyle = '#ffffff';
                  context.stroke();
                  // 添加路径
                  path = new Path2D();
                  path.arc(ctr.heart_x_begin_left, ctr.heart_y_begin_left, size3*4, 0, 2*Math.PI);
                  paths.push({
                    type: 'line',
                    cursor: 'e-resize',
                    dir: 'x',
                    path: path,
                    key: 'heart_x_begin_left'
                  });
                  // 红色中
                  context.beginPath();
                  context.arc(ctr.heart_x_begin_left+(centerX-ctr.heart_x_begin_left)/2, ctr.heart_y_begin_left, size3*4, 0, 2*Math.PI);
                  context.closePath();
                  context.lineWidth = size3;
                  context.strokeStyle = '#ffffff';
                  context.stroke();
                  // 添加路径
                  path = new Path2D();
                  path.arc(ctr.heart_x_begin_left+(centerX-ctr.heart_x_begin_left)/2, ctr.heart_y_begin_left, size3*4, 0, 2*Math.PI);
                  paths.push({
                    type: 'line',
                    cursor: 'n-resize',
                    dir: 'y',
                    path: path,
                    key: 'heart_y_begin_left'
                  });

                  // 红色右
                  context.beginPath();
                  context.arc(ctr.heart_x_end_right, ctr.heart_y_end_right, size3*4, 0, 2*Math.PI);
                  context.closePath();
                  context.lineWidth = size3;
                  context.strokeStyle = '#ffffff';
                  context.stroke();
                  // 添加路径
                  path = new Path2D();
                  path.arc(ctr.heart_x_end_right, ctr.heart_y_end_right, size3*4, 0, 2*Math.PI);
                  paths.push({
                    type: 'line',
                    cursor: 'e-resize',
                    dir: 'x',
                    path: path,
                    key: 'heart_x_end_right'
                  });
                  // 红色中
                  context.beginPath();
                  context.arc(centerX+(ctr.heart_x_end_right-centerX)/2, ctr.heart_y_end_right, size3*4, 0, 2*Math.PI);
                  context.closePath();
                  context.lineWidth = size3;
                  context.strokeStyle = '#ffffff';
                  context.stroke();
                  // 添加路径
                  path = new Path2D();
                  path.arc(centerX+(ctr.heart_x_end_right-centerX)/2, ctr.heart_y_end_right, size3*4, 0, 2*Math.PI);
                  paths.push({
                    type: 'line',
                    cursor: 'n-resize',
                    dir: 'y',
                    path: path,
                    key: 'heart_y_end_right'
                  });

                  this.paths.push(...paths.reverse());
              }
            },

            // 画矩形
            drawRect(data, onlyImg) {
                var list = data;
                var context = this.context;
                var paths = [];

                var path = null;

                for(var i = 0; i < list.length; i++) {
                    var item = list[i];
                    if(item.isDelete) {
                        continue;
                    }
                    if(!item.mark) {
                        continue;
                    }
                    var confidence = item.confidence;
                    var label = item.name;
                    var color = config[label] || 'rgb(0,0,0)';

                    if (confidence !== 1) {
                        label = label + " " + confidence;
                    }
                    var xmin = item.xmin+this.image.leftDis;
                    var ymin = item.ymin+this.image.topDis;
                    var xmax = item.xmax+this.image.leftDis;
                    var ymax = item.ymax+this.image.topDis;

                    var size1 = 60;
                    var size2 = 8;
                    var size3 = 4;

                    context.fillStyle = color;
                    context.strokeStyle = color;
                    context.lineWidth = size2;
                    context.font = size1+"px 微软雅黑"
                    context.beginPath();
                    context.moveTo(xmin, ymin);
                    context.lineTo(xmin, ymax);
                    context.lineTo(xmax, ymax);
                    context.lineTo(xmax, ymin);
                    context.lineTo(xmin, ymin);
                    context.fillText(label, xmin, ymin - 1)
                    context.fillRect(xmin, ymin - size1, context.measureText(label).width, size1);
                    context.closePath();
                    context.stroke();
                    context.fillStyle = "white"
                    context.fillText(label, xmin, ymin - 1);

                    if(!onlyImg) {
                        if (this.editRectIndex == i) {
                            // 添加左上
                            context.beginPath();
                            context.arc(xmin, ymin, size2 * 2, 0, 2 * Math.PI);
                            context.closePath();
                            context.lineWidth = size2;
                            context.strokeStyle = '#ffffff';
                            context.stroke();
                            // 添加路径
                            path = new Path2D();
                            path.arc(xmin, ymin, size2 * 2, 0, 2 * Math.PI);
                            paths.push({
                                type: 'rect',
                                cursor: 'nw-resize',
                                dir: 'xy',
                                path: path,
                                key: ['xmin', 'ymin'],
                                index: i
                            });

                            // 添加左下
                            context.beginPath();
                            context.arc(xmin, ymax, size2 * 2, 0, 2 * Math.PI);
                            context.closePath();
                            context.lineWidth = size2;
                            context.strokeStyle = '#ffffff';
                            context.stroke();
                            // 添加路径
                            path = new Path2D();
                            path.arc(xmin, ymax, size2 * 2, 0, 2 * Math.PI);
                            paths.push({
                                type: 'rect',
                                cursor: 'sw-resize',
                                dir: 'xy',
                                path: path,
                                key: ['xmin', 'ymax'],
                                index: i
                            });

                            // 添加右上
                            context.beginPath();
                            context.arc(xmax, ymin, size2 * 2, 0, 2 * Math.PI);
                            context.closePath();
                            context.lineWidth = size2;
                            context.strokeStyle = '#ffffff';
                            context.stroke();
                            // 添加路径
                            path = new Path2D();
                            path.arc(xmax, ymin, size2 * 2, 0, 2 * Math.PI);
                            paths.push({
                                type: 'rect',
                                cursor: 'ne-resize',
                                dir: 'xy',
                                path: path,
                                key: ['xmax', 'ymin'],
                                index: i
                            });

                            // 添加右下
                            context.beginPath();
                            context.arc(xmax, ymax, size2 * 2, 0, 2 * Math.PI);
                            context.closePath();
                            context.lineWidth = size2;
                            context.strokeStyle = '#ffffff';
                            context.stroke();
                            // 添加路径
                            path = new Path2D();
                            path.arc(xmax, ymax, size2 * 2, 0, 2 * Math.PI);
                            paths.push({
                                type: 'rect',
                                cursor: 'se-resize',
                                dir: 'xy',
                                path: path,
                                key: ['xmax', 'ymax'],
                                index: i
                            });
                        }

                        let xysize = 24;

                        // 添加中心
                        var xcenter = xmin+(xmax-xmin)/2;
                        var ycenter = ymin+(ymax-ymin)/2;
                        context.beginPath();
                        context.moveTo(xcenter-xysize, ycenter);
                        context.lineTo(xcenter+xysize, ycenter);
                        context.closePath();
                        context.lineWidth = size2/2;
                        context.strokeStyle = '#ffffff';
                        context.stroke();
                        context.beginPath();
                        context.moveTo(xcenter, ycenter-xysize);
                        context.lineTo(xcenter, ycenter+xysize);
                        context.closePath();
                        context.lineWidth = size2/2;
                        context.strokeStyle = '#ffffff';
                        context.stroke();
                        //添加路径
                        path = new Path2D();
                        path.rect(xcenter-xysize, ycenter-xysize, xysize*2, xysize*2);
                        paths.push({
                            type: 'rect',
                            cursor: this.editRectIndex == i ? 'move' : 'pointer',
                            dir: 'xy',
                            path: path,
                            index: i
                        });
                    }
                }
                this.paths.push(...paths.reverse());
            },

            // 画添加矩形
            drawAddRect() {
                let xmin = this.add.xmin;
                let ymin = this.add.ymin;
                let xmax = this.add.xmax;
                let ymax = this.add.ymax;

                let label = this.add.name;
                let color = config[label] || 'rgb(0,0,0)';
                let context = this.context;

                var size1 = 60;
                var size2 = 8;
                var size3 = 4;

                context.fillStyle = color;
                context.strokeStyle = color;
                context.lineWidth = size2;
                context.font = size1+"px 微软雅黑"
                context.beginPath();
                context.moveTo(xmin, ymin);
                context.lineTo(xmin, ymax);
                context.lineTo(xmax, ymax);
                context.lineTo(xmax, ymin);
                context.lineTo(xmin, ymin);
                context.fillText(label, xmin, ymin - 1)
                context.fillRect(xmin, ymin - size1, context.measureText(label).width, size1);
                context.closePath();
                context.stroke();
                context.fillStyle = "white"
                context.fillText(label, xmin, ymin - 1);
            },

            // 获取图片
            getImageFile(data) {
                this.showLine = true; // 是否显示线
                this.oldData = JSON.parse(JSON.stringify(data));
                this.newData = JSON.parse(JSON.stringify(data));

                this.drawData();

                // 保存图片
                var base64 = this.oCanvas.toDataURL('image/png');
                return base64ToFile(base64, '数据.png');
            }
          }


          const waitTimeout = function (time) {
            return new Promise((resolve, reject) => {
              setTimeout(() => {
                resolve();
              }, time);
            })
          }

          // base64转文件
          function base64ToFile(base64, fileName) {
            var arr = base64.split(','),
              mime = arr[0].match(/:(.*?);/)[1],
              bstr = atob(arr[1]),
              n = bstr.length,
              u8arr = new Uint8Array(n);
            while (n--) {
              u8arr[n] = bstr.charCodeAt(n);
            }
            var theBlob = new Blob([u8arr], { type: mime });
            theBlob.lastModifiedDate = new Date();  // 文件最后的修改日期
            theBlob.name = fileName;                // 文件名
            return new File([theBlob], fileName, {type: theBlob.type, lastModified: Date.now()});
          }

        // 获取当前保存的Objects
        function getSaveObjects() {
            let objData = JSON.parse(JSON.stringify(objects));
            let currentObj = infos[image_uir + "_current"];
            for(let i = 0; i < currentObj.length; i++) {
                let index = currentObj[i].index;
                if(index >= 0) {
                    objData[index] = currentObj[i];
                } else {
                    objData.push(currentObj[i]);
                }
            }
            // 删除isDelete节点
            objData = objData.filter(item => !item.isDelete);
            // 设置阈值
            let threshold = document.getElementById("threshold").value;
            objData.forEach(item => {
                item.confidence = item.confidence > threshold ? 1 : item.confidence;
            })
            return objData;
        }

        // 保存诊断数据
        function saveDiagnosisData() {
            $.ajax({
                url: "http://" + window.location.host + "/updatejson",//json文件位置，文件名
                type: "POST",//请求方式为get
                contentType: 'application/json',
                data: JSON.stringify({
                    dst: image_uir.replace('/data', ''),
                    ctr: infos[image_uir + "ctr"],
                    objects: getSaveObjects()
                }),
                success: function (res) {//请求成功完成后要执行的方法
                    window.location.reload();
                }
            })
        }

        // 获取并设置表单
        function setForm() {
            $.ajax({
                url: "http://" + window.location.host + "/get_conclusion",//json文件位置，文件名
                type: "POST",
                data: {
                    sopid: image_uir
                },
                success: function (res) {//请求成功完成后要执行的方法
                    $('#performance').val(res.bx || '');
                    $('#yj').val(res.yj || '');
                }
            })
        }

        // 保存表单提交
        function saveForm() {
            let image = oEdit.getImageFile({
                line: infos[image_uir + "ctr"],
                rect: infos[image_uir + "_current"]
            });

            let formData = new FormData();
            formData.append('thumbnail', image);
            formData.append("bx", $('#performance').val());
            formData.append("sopid", $('#sop_id').val());
            formData.append("yj", $('#yj').val());

            $.ajax({
                url: "http://" + window.location.host + "/update_conclusion",//json文件位置，文件名
                type: "POST",
                // 不修改 Content-Type 属性，使用 FormData 默认的 Content-Type 值
                contentType: false,
                // 不对 FormData 中的数据进行 url 编码，而是将 FormData 数据原样发送到服务器
                processData: false,
                data: formData,
                success: function (res) {//请求成功完成后要执行的方法
                    // toastr.success('保存成功');
                    window.location.reload();
                }
            })
        }


        $(function () {
            toastr.options.positionClass = 'toast-top-center';
            toastr.options.timeOut = 1000;
            $.ajax({
                url: "http://" + window.location.host + "/xray/getSystemSettings",
                type: "get",
                success: function (res) {//请求成功完成后要执行的方法
                    let data = JSON.parse(res.data);
                    let obj = data[0].fields;
                    $('#orgName').val(obj.org_name);
                    $('#doctorName').val(obj.doctor);
                }
            })

            setDownList();

            // 隐藏右键菜单
            $(window).on('click', () => {
                $('.right-menu').hide();
            })
            // 绑定删除
            $('.right-menu.del').on('click', '.item', () => {
                oEdit.deleteRectData();
            })
            // 绑定页面按下Delete事件
            window.addEventListener('keyup', (e) => {
                if(e.keyCode == 46 && oEdit.visible == true && oEdit.editRectIndex != -1) {
                    oEdit.deleteIndex = oEdit.editRectIndex;
                    oEdit.deleteRectData();
                }
            })
        })
        function saveSystemModal() {
            let orgName = $('#orgName').val();
            let doctorName = $('#doctorName').val();
            if(!orgName) {
                toastr.warning('请输入单位名称');
                return;
            }
            if(!doctorName) {
                toastr.warning('请输入报告医生');
                return;
            }
            $.ajax({
                url: "http://localhost:8088/xray/updateSystemSettings/",//json文件位置，文件名
                type: "POST",
                data: {
                    org_name: orgName,
                    doctor: doctorName,
                },
                success: function (res) {//请求成功完成后要执行的方法
                  // toastr.success('保存成功');
                }
            })
        }

        // 设置下拉框
        function setDownList() {
            let html = '';
            for(let key in config) {
                html += `<div class="item" data-key="${key}" style="color:${config[key]}">${key}</div>`;
            }
            $('.right-menu.add .list').html(html);
            $('.right-menu.add .list').on('click', '.item', function () {
                let key = this.dataset.key;
                oEdit.addRect(key);
            })
            $('.right-menu.add .new').on('click', function (e) {
                e.stopPropagation();
            })
            $('.right-menu.add .new').on('click', '.btn', function (e) {
                let key = $('.right-menu.add .new input').val();
                oEdit.addRect(key);
                $('.right-menu.add').hide();
            })
        }

    </script>


{% endblock script %}